package cn.edu.xjtu.nbrash.xbarsuite.floatbutton;

import android.content.Context;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;

/**
 * FloatWidget.java
 *
 * @author Jingkai Tang jingkaitang@gmail.com
 * @version 0.0.1 Nov 13, 2014 9:48:56 PM
 *
 */

public class FloatWidget {

	private static final String TAG = FloatWidget.class.getName();

	private final WindowManager windowManager;
	private final WindowManager.LayoutParams layoutParams;
	private final View view;

	private FloatWidgetOnClickListener onClickListener;

	public FloatWidget(final View view) {
		this.view = view;
		this.windowManager = (WindowManager) view.getContext()
				.getSystemService(Context.WINDOW_SERVICE);
		this.layoutParams = new WindowManager.LayoutParams();
		this.onClickListener = null;
		
		layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
		
		layoutParams.format = PixelFormat.RGBA_8888;

		layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		
		view.setOnTouchListener(new OnTouchListener() {

			int x = 0;
			int y = 1;
			int[] position = new int[2];
			int[] motion = new int[2];

			/** 
			 * use this boolean variable to judge the view is moved
			 * if not, when it motion event up 
			 */
			boolean isMoved = false;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						isMoved = false;
						motion[x] = (int) event.getRawX();
						motion[y] = (int) event.getRawY();
						position[x] = layoutParams.x;
						position[y] = layoutParams.y;
						break;

					case MotionEvent.ACTION_MOVE:
						layoutParams.x = position[x] + (int) event.getRawX()
								- motion[x];
						layoutParams.y = position[y] + (int) event.getRawY()
								- motion[y];
						if (layoutParams.x != position[x]
								&& layoutParams.y != position[y]) {
							isMoved = true;
						}
						windowManager.updateViewLayout(view, layoutParams);
						break;

					case MotionEvent.ACTION_UP:
						if (!isMoved) {
							if (onClickListener != null) {
								onClickListener.onClick(view);
							} else {
								Log.e(TAG,
										"FloatWidgetOnClickListener has not been setted!");
							}
						}
						break;
				}
				return false;
			}
		});
	}

	public WindowManager.LayoutParams getLayoutParams() {
		return layoutParams;
	}

	public void add() {
		windowManager.addView(view, layoutParams);
	}

	public void remove() {
		windowManager.removeView(view);
	}

	public void show() {
		view.setVisibility(View.VISIBLE);
	}

	public void hide() {
		view.setVisibility(View.INVISIBLE);
	}

	public void setOnClickListener(FloatWidgetOnClickListener onClickListener) {
		this.onClickListener = onClickListener;
	}
}
